package xyz.lwm.lazycat.transaction.execute;

import xyz.lwm.lazycat.transaction.policy.TransactionPolicy.CheckedSupplier;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
 * datasource wrapper for transaction
 *
 * @author lwm
 */
public class TransactionDatasource implements DataSource {

    private final DataSource delegate;

    public TransactionDatasource(DataSource delegate) {
        this.delegate = delegate;
    }

    @Override
    public Connection getConnection() throws SQLException {
        return wrap(delegate::getConnection);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return wrap(() -> delegate.getConnection(username, password));
    }

    private Connection wrap(CheckedSupplier<Connection> connSupplier) throws SQLException {
        // get connection of transaction first
        Transaction current = TransactionManager.current();
        if (current.getConnection() != null) {
            return current.getConnection();
        }
        // get datasource connection
        try {
            Connection connection = connSupplier.get();
            if (current.isOpen()) {
                connection.setAutoCommit(false);
                connection.setReadOnly(current.isReadOnly());
                Isolation isolation = current.getIsolation();
                if (isolation != Isolation.DEFAULT) {
                    connection.setTransactionIsolation(isolation.level);
                }
                ((TransactionImpl) current).setConnection(connection);
            }
            return connection;
        } catch (Throwable e) {
            throw new SQLException(e);
        }
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return delegate.getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        delegate.setLogWriter(out);
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        delegate.setLoginTimeout(seconds);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return delegate.getLoginTimeout();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return delegate.getParentLogger();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return delegate.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return delegate.isWrapperFor(iface);
    }

}
